/*
 * SunSpotHostApplication.java
 *
 * Created on Jun 14, 2009 3:52:41 PM;
 */

package org.sunspotworld;

import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.peripheral.radio.IRadioPolicyManager;
import com.sun.spot.io.j2me.radiostream.*;
import com.sun.spot.io.j2me.radiogram.*;
import com.sun.spot.util.IEEEAddress;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.microedition.io.*;
import javax.swing.JFrame;
import org.gunncs.RobotModel;
import org.gunncs.ui.DashBoardComponent;


/**
 * Sample Sun SPOT host application
 */
public class SunSpotHostApplication {

    /**
     * Print out our radio address.
     */
    public boolean running;
    public boolean connected;

    public void run() {
        long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
        System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));
        RadiogramConnection rcvConn = null;
        Datagram dg = null;
        try {
            rcvConn = (RadiogramConnection) Connector.open("radiogram://:38");
            dg = rcvConn.newDatagram(rcvConn.getMaximumLength());
        } catch (IOException ex) {
            Logger.getLogger(SunSpotHostApplication.class.getName()).log(Level.SEVERE, null, ex);
            running = false;
        }

        JFrame viewer = new JFrame("Dashboard");
        viewer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DashBoardComponent board = new DashBoardComponent(new RobotModel());
        viewer.add(board);
        viewer.setSize(800, 500);
        viewer.setVisible(true);
        viewer.repaint();

        while(running){
            viewer.repaint();
            dg.reset();
            String ts = "";
            try {
                rcvConn.receive(dg);
                ts = dg.readUTF();
            } catch (IOException ex) {
                Logger.getLogger(SunSpotHostApplication.class.getName()).log(Level.SEVERE, null, ex);
            }
            if(!(ts.equals(""))){
              
              System.out.println(ts);
                try{
                    if(connected){
                        board.getRobotModel().updateStatus(ts.split("\t"));
                    }else{
                        RobotModel newbot = RobotModel.robotFromStatus(ts.split("\t"));
                        board.setRobotModel(newbot);
                        connected = true;
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
                
                System.out.println("------");
            }
        }
    }

    /**
     * Start up the host application.
     *
     * @param args any command line arguments
     */
    public static void main(String[] args) {
        SunSpotHostApplication app = new SunSpotHostApplication();
        app.running = true;
        app.run();
    }
}
